import { reqLogin, reqLogout } from '@/api/user'
const initState = JSON.parse(localStorage.getItem('user')) || {
  token: '', //用户登陆后的唯一标识
  name: '', //用户名
}
export default {
  namespaced: true,
  state: initState,
  actions: {
    async login({ commit }, { phone, password }) {
      const result = await reqLogin(phone, password)
      commit('LOGIN', result)
    },
    async logout({ commit }) {
      await reqLogout()
      commit('LOGOUT')
    },
  },
  mutations: {
    LOGIN(state, user) {
      // 存储到vuex中
      state.name = user.name
      state.token = user.token
      // 存储到localStorage中
      localStorage.setItem(
        'user',
        JSON.stringify({
          name: user.name,
          token: user.token,
        })
      )
    },
    LOGOUT(state) {
      state.name = ''
      state.token = ''
      localStorage.removeItem('user')
    },
  },
}
